﻿using Ozone.Common;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ozone.Help
{
    public class RedisKeyWatcher
    {
        private readonly ConnectionMultiplexer _redis;
        private readonly ISubscriber _subscriber;
        private readonly IDatabase _db;

        public RedisKeyWatcher(string connectionString, int dbIndex = 0)
        {
            _redis = ConnectionMultiplexer.Connect(connectionString);
            _subscriber = _redis.GetSubscriber();
            _db = _redis.GetDatabase(dbIndex);
        }

        /// <summary>
        /// 开始监控键空间
        /// </summary>
        /// <param name="dbIndex"></param>
        public void StartWatching(int dbIndex = 0)
        {
            // 订阅指定数据库的所有键事件
            var channel = $"__keyspace@{dbIndex}__:*";
            _subscriber.Subscribe(channel, (redisChannel, value) =>
            {
                var channelStr = redisChannel.ToString();
                string[] key = channelStr.Split(':');

                RadisService.KeyChange(key[1]);
            });
        }




        /// <summary>
        /// 停止监控 键空间
        /// </summary>
        public void StopWatching() => _subscriber.UnsubscribeAll();







        /// <summary>
        /// 查询Key值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<string> GetKeyValueAsync(string key)
        {
            return await _db.StringGetAsync(key);
        }



        /// <summary>
        /// 更新Key值 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expiry"></param>
        /// <param name="when"></param>
        /// <returns></returns>
        public async Task<bool> SetKeyValueAsync(string key, string value,
            TimeSpan? expiry = null, When when = When.Always)
        {
            return await _db.StringSetAsync(key, value, expiry, when);
        }

        /// <summary>
        /// 判断Key值是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool KeyExists(string key)
        {
            return _db.KeyExists(key);
        }

    }
}
